//
//  SearchProjectViewController.m
//  OutesIOS
//
//  Created by norman on 2018/11/7.
//  Copyright © 2018 norman. All rights reserved.
//

#import "SearchProjectViewController.h"
#import "ProjectDetailViewController.h"
#import "ProjectStatusModifyViewController.h"
#import "ProjectManager.h"
#import "ProjectData.h"
#import "ProjectManager.h"
#import "Project_Step8ViewController.h"
#import "TwoLineWithDateCell.h"
#import "ProjectTableViewCell.h"
#import "Project_Step1ViewController.h"
#import "ProjectListResp.h"
#import "ProjectImagesViewController.h"
#import "HttpTool.h"

#define CELL_IDENTIFIER @"CELL_IDENTIFIER"

@interface SearchProjectViewController ()<UISearchBarDelegate, UIDocumentInteractionControllerDelegate>{
    int page_index;
}

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataSource;

@property (nonatomic,strong) UISearchBar *projectSearchBar;
@property (nonatomic,copy) NSString *sw;
@property (nonatomic,strong) UIDocumentInteractionController *documentController;

@end

@implementation SearchProjectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupSearchView];
    [self setupViews];
    [self initData];
}

- (void)setupSearchView {
    self.projectSearchBar = [[UISearchBar alloc]init];
    self.projectSearchBar.placeholder = @"请输入项目相关信息";
    //修改placeholder字体的颜色和大小
    UITextField * searchField = [self.projectSearchBar valueForKey:@"_searchField"];
    [searchField setValue:CM_PLACEHOLDER_TEXT_COLOR forKeyPath:@"_placeholderLabel.textColor"];
    [searchField setValue:[UIFont systemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    if (@available(iOS 11.0, *)) {
        [[self.projectSearchBar.heightAnchor constraintEqualToConstant:44.0] setActive:YES];
    }
    self.projectSearchBar.showsCancelButton = NO;
    self.projectSearchBar.delegate = self;
    self.navigationItem.titleView = self.projectSearchBar;
}

- (void)setupViews{
    self.tableView = ({
        UITableView *tableView = [[UITableView alloc] initWithFrame:[UIView frameWithOutNav] style:UITableViewStylePlain];
        [tableView setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
        [tableView setSeparatorColor: UIColor16(0xeeeeee)];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        [tableView registerClass:[ProjectTableViewCell class] forCellReuseIdentifier:CELL_IDENTIFIER];
        [self.view addSubview:tableView];
        tableView;
    });
    
    // 下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
    // 上拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
}


-(void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
//    [self loadAllSubProjectsbegin:beginIndex end:endIndex];
}

#pragma mark - 初始化数据
- (void)initData{
    page_index = 1;
    self.dataSource = [[NSMutableArray alloc] init];
}

- (void)refreshData {
    page_index = 1;
    [self loadData];
}

- (void)loadMoreData {
    if (self.dataSource.count == LIST_PAGE_ITEM_COUNTS*page_index) {
        page_index++;
        [self loadData];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}


- (void)loadData {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:self.sw forKey:@"sw"];
    [param setValue:[NSNumber numberWithInteger:page_index] forKey:@"page_index"];
    [param setValue:[NSNumber numberWithInteger:LIST_PAGE_ITEM_COUNTS] forKey:@"page_size"];
    
    [HttpClient getWithUrl:HTTP_GET_PROJECT_LIST_SEARCH token:[[AccountManager manager]token] paramDic:param resultClass:[ProjectListResp class] success:^(ProjectListResp *obj) {
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
        if (self->page_index == 1) {
            [self.dataSource removeAllObjects];
            if (obj.projects == nil || obj.projects.count == 0) {
                [MBProgressHUD showSuccess:@"没有查询到相关项目！"];
                return;
            }
        }
        if (obj.projects && obj.projects.count > 0) {
            [self.dataSource addObjectsFromArray:obj.projects];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView.mj_footer endRefreshing];
        [self.tableView.mj_header endRefreshing];
        [self.tableView reloadData];
        CMLog(@"获取项目失败：%@", error);
    }];
}

- (void)deleteProject:(NSInteger)index {
    ProjectData *item = [self.dataSource objectAtIndex:index];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setValue:item.project_id forKey:@"project_id"];
    [HttpClient getWithUrl:HTTP_GET_PROJECT_DELETE token:[[AccountManager manager]token] paramDic:param resultClass:[CommonResponse class] success:^(CommonResponse *obj) {
        [self refreshData];
    } failure:^(NSError *error) {
    }];
}

#pragma mark - UISearchBar代理
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    //已经开始编辑
    NSLog(@"已经开始编辑");
}// called when text starts editing

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    self.sw = searchBar.text;
    [self refreshData];
}// called when text ends editing


- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    //searchText是searchBar上的文字 每次输入或删除都都会打印全部
}// called when text changes (including clear)

//点击键盘上搜索时的相应事件
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    self.sw = searchBar.text;
    [self refreshData];
}// called when keyboard search button pressed

#pragma mark - UITableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ProjectTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CELL_IDENTIFIER];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    ProjectData *item = [self.dataSource objectAtIndex:indexPath.row];
    [cell setProjectData:item];
    cell.setProjectImageCB = ^(int index) {
        if (index == 0) {
            if (![Tools isEmpty:item.report]) {
                [self viewProjectReport:item];
            }
        } else {
            ProjectImagesViewController *vc = [ProjectImagesViewController new];
            vc.project_id = item.project_id;
            vc.images = item.images;
            vc.is_5c = YES;
            vc.imageChanged = ^(NSString *images){
                item.images = images;
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationAutomatic];
            };
            [self.navigationController pushViewController:vc animated:YES];
        }
    };
    if (item.state != 2) {
        //滑动按钮
        cell.rightUtilityButtons = [self rightButtons];
        cell.delegate = self;
        cell.tag = indexPath.row;
    }
    return cell;
}

-(NSArray *)rightButtons {
    NSMutableArray *rightUtilityButtons = [NSMutableArray new];
    [rightUtilityButtons sw_addUtilityButtonWithColor:[UIColor redColor] title:@"删除"];
    return rightUtilityButtons;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [ProjectTableViewCell cellHeight];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    ProjectData *item = [self.dataSource objectAtIndex:indexPath.row];
    Project_Step1ViewController *vc = [Project_Step1ViewController new];
    vc.project_id = item.project_id;
    [self.navigationController pushViewController:vc animated:YES];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
//    ProjectListResp *group = [self.dataSource objectAtIndex:section];
//    CGFloat h = [Tools sizeOfSingleLineText:@"高度" withSize:kListTitleFontSize].height + 30;
//
//    UIView *header = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, h)];
//    header.backgroundColor = [UIColor whiteColor];
//    //时间
//    UILabel *lbDate = [UILabel labelSingleLineFontSize:kListTitleFontSize content:group.date];
//    if (section > 0) {
//        lbDate.text = @"2018-10-22";
//    }
//    lbDate.textColor = BSBlackTextColor;
//    lbDate.width += 10;
//    lbDate.y = 30;
//    [header addSubview:lbDate];
//
//    UIImageView *dot = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"dot"]];
//    dot.width = 5;
//    dot.height = 5;
//    dot.x = 10;
//    dot.centerY = lbDate.centerY;
//    lbDate.x = CGRectGetMaxX(dot.frame) + 5;
//    [header addSubview:dot];
//    return header;
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, CGFLOAT_MIN)];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    CGFloat h = [Tools sizeOfSingleLineText:@"高度" withSize:kListTitleFontSize].height + 30;
//    return h;
    return CGFLOAT_MIN;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, CGFLOAT_MIN)];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

#pragma mark - 滑动按钮代理协议
/**
 *  右侧滑动按钮点击事件
 *
 *  @param cell  单元cell
 *  @param index 下标
 */
-(void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index{
    switch (index) {
        case 0:{
            [self deleteProject:cell.tag];
            break;
        }
            
        default:
            break;
    }
    [cell hideUtilityButtonsAnimated:YES];
}


/**
 *  滑动的时候把其他的隐藏掉
 *
 *  @param cell cell
 *
 *  @return 隐藏其他的cell
 */
-(BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell{
    return YES;
}


- (void)viewProjectReport:(ProjectData *)item {
    UIAlertController * alertController = [UIAlertController alertControllerWithTitle: @"项目报告" message: nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertController addAction: [UIAlertAction actionWithTitle:@"在线查看报告" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        Project_Step8ViewController *view = [Project_Step8ViewController new];
        view.report = item.report;
        view.project_name = item.project_name;
        [self.navigationController pushViewController:view animated:YES];
    }]];
    [alertController addAction: [UIAlertAction actionWithTitle:@"下载报告到本地" style: UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self downloadProjectReport:item.report];
    }]];
    
    [alertController addAction: [UIAlertAction actionWithTitle: @"取消" style: UIAlertActionStyleCancel handler:nil]];
    [self presentViewController: alertController animated: YES completion: nil];
}

#pragma mark -文件下载并查看
- (void)downloadProjectReport:(NSString*)file {
    file = [file stringByReplacingOccurrencesOfString:@".pdf" withString:@".xlsx"];
    NSString *fullPath = [Tools getResourceFullPath:file];
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"下载中...";
    // 再设置模式
    hud.mode = MBProgressHUDModeDeterminateHorizontalBar;
    [hud show:YES];
    [HttpTool download:fullPath progress:^(NSProgress *downloadProgress) {
        hud.progress = downloadProgress.completedUnitCount/downloadProgress.totalUnitCount;
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        [hud hide:YES];
        [self openFileViewController:filePath];
    }];
}

-(void)openFileViewController:(NSURL *)filePath{
    if (filePath != nil) {
        if (_documentController == nil) {
            _documentController = [UIDocumentInteractionController interactionControllerWithURL:filePath];
            _documentController.delegate = self;
        }else {
            _documentController.URL = filePath;
        }
    }
    [_documentController presentPreviewAnimated:YES];
}


- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)interactionController {
    return self;
}

-(UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller{
    return self.view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController*)controller
{
    return self.view.frame;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
